package main

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	path2 "path"
	"time"
)

func main() {
	r := gin.Default()

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"msg": "pong"})
	})

	r.GET("/get", func(c *gin.Context) {
		//name := c.Query("name")
		name := c.DefaultQuery("name", "hello")
		c.JSON(http.StatusOK, gin.H{"name": name})
	})

	r.GET("/json", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"html": "<b>Hello, world!</b>",
		})
	})

	r.GET("/purejson", func(c *gin.Context) {
		c.PureJSON(http.StatusOK, gin.H{
			"html": "<b>Hello, world!</b>",
		})
	})

	r.POST("/login", func(c *gin.Context) {

		name := c.PostForm("name")
		age := c.PostForm("age")

		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"age":  age,
		})
	})

	r.GET("/:name/:age", func(c *gin.Context) {
		name := c.Param("name")
		age := c.Param("age")
		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"age":  age,
		})
	})

	r.POST("/testBind", func(c *gin.Context) {
		var login Login
		c.ShouldBind(&login)

		c.JSON(http.StatusOK, gin.H{
			"name": login.Name,
			"age":  login.Age,
		})

	})

	r.POST("/upload", func(c *gin.Context) {
		file, _ := c.FormFile("file")
		log.Println(file.Filename)
		path := path2.Join("./", file.Filename)
		c.SaveUploadedFile(file, path)
		c.JSON(http.StatusOK, gin.H{
			"state": "ok",
		})

	})

	//v1 := r.Group("/v1")
	//{
	//	v1.POST("/login", loginEndpoint)
	//	v1.POST("/submit", submitEndpoint)
	//	v1.POST("/read", readEndpoint)
	//}
	//
	//// Simple group: v2
	//v2 := r.Group("/v2")
	//{
	//	v2.POST("/login", loginEndpoint)
	//	v2.POST("/submit", submitEndpoint)
	//	v2.POST("/read", readEndpoint)
	//}

	r.GET("/authLogin", computeTime(false), func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"msg": "ok"})
	})

	r.Run("localhost:8080")
}

type Login struct {
	Name string `json:"name" form:"name" binding:"required"`
	Age  int    `json:"age" form:"age"`
}

func computeTime(a bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		now := time.Now()
		c.Next()
		c.Set("name", "houry")
		total := time.Since(now)
		log.Println("一共耗时:", total)
	}
}
